package com.sugon.modules.sparepart.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.cait.bpmsuite.api.bpmmodle.BPMWorkItem;
import com.sugon.entity.MaterialBaseEntity;
import com.sugon.entity.MaterialRecordEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.modules.sparepart.consts.MaterialBaseConst;
import com.sugon.modules.sparepart.consts.MaterialBaseProgress;
import com.sugon.modules.sparepart.model.vo.CommonApproveParamVO;
import com.sugon.modules.sparepart.service.ISparepartMaterialBaseManager;
import com.sugon.modules.sys.service.INoticeManager;
import com.sugon.modules.workflow.IWorkFlowManager;
import com.sugon.service.*;
import com.sugon.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SparepartMaterialBaseManagerImpl implements ISparepartMaterialBaseManager {

    @Autowired
    private MaterialBaseService materialBaseService;
    @Resource
    private MaterialRecordService materialRecordService;
    @Autowired
    private IWorkFlowManager workFlowManager;
    @Autowired
    private SysOaProcessService processService;
    @Resource
    private SpareStorePosService spareStorePosService;
    @Resource
    private SparePartConsumRecordService sparePartConsumRecordService;
    @Resource
    private INoticeManager noticeManager;
    @Resource
    private SysUserService userService;

    /**
     * commitApprove
     *
     * @param materialBase 领料单
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean commitApprove(MaterialBaseEntity materialBase) {
        materialBase.setProgress(MaterialBaseProgress.WAIT_APPROVE);
        materialBase.setIsCheck(0);
        materialBase.setCheckRemark(null);
        boolean updateFlag = materialBaseService.update(materialBase) > 0;
        if (updateFlag) {
            // 开始OA审批流程
            workFlowManager.startAndCompleteFirstWorkItem(materialBase.getId(), materialBase.getPicker(), materialBase.getMaterCode(), materialBase.getApproverUnionId());
            // 给审批人推送企业微信
            noticeManager.pushLldspNotice(materialBase);
        }
        return updateFlag;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean cancel(MaterialBaseEntity materialBase) {
        // 先取出进度
        Integer progress = materialBase.getProgress();
        materialBase.setProgress(MaterialBaseProgress.CANCEL);
        boolean updateFlag = materialBaseService.update(materialBase) > 0;
        if (updateFlag) {
            // 如果已提交审核但未出库完毕，取消领料时需要终止流程并记录结果
            if (CollectionUtil.newArrayList(MaterialBaseProgress.WAIT_APPROVE, MaterialBaseProgress.WAIT_OUTBOUND, MaterialBaseProgress.NOT_PASSED).contains(progress)) {
                workFlowManager.terminateProcessInstance(materialBase.getId(), materialBase.getProcInstId());
            }
            // 释放冻结备件库存
            List<MaterialRecordEntity> materialList = materialRecordService.queryByMater(materialBase.getId());
            if (CollectionUtil.isNotEmpty(materialList)) {
                for (MaterialRecordEntity materialRecord : materialList) {
                    spareStorePosService.realtimeUpdateStorePosStock(materialRecord.getPostionId());
                }
            }
        }
        return updateFlag;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean invalid(MaterialBaseEntity materialBase) {
        // 先取出进度
        Integer progress = materialBase.getProgress();
        materialBase.setProgress(MaterialBaseProgress.INVALID);
        boolean updateFlag = materialBaseService.update(materialBase) > 0;
        if (updateFlag) {
            /*
                1、删除出库记录
                2、删除报废记录
                3、实时更新备件库位的库存和锁定库存数
                4、实时更新备件库存数
                5、删除备件出库事务记录
             */

            // 释放冻结备件库存
            List<MaterialRecordEntity> materialList = materialRecordService.queryByMater(materialBase.getId());
            if (CollectionUtil.isNotEmpty(materialList)) {
                for (MaterialRecordEntity materialRecord : materialList) {
                    spareStorePosService.realtimeUpdateStorePosStock(materialRecord.getPostionId());
                }
            }


//            // 1、生成报废记录
//            scarpListService.doScrap(out);
//            // 2、实时更新备件库位的库存和锁定库存数
//            spareStorePosService.realtimeUpdateStorePosStock(posId);
//            // 3、实时更新备件库存数
//            sparePartDao.realtimeUpdateStock(spareCode);
//            // 4、生成备件出库事务记录
//            sparePartTransactionService.generateOutTransaction(out);


        }
        return updateFlag;
    }

    @Override
    public String check(CommonApproveParamVO approveParam) {
        // 跳转地址
        String directUrl = "";
        Integer approveState = approveParam.getState();
        String workItemId = approveParam.getWorkItemId();
        BPMWorkItem bpmWorkItem = approveParam.getBpmWorkItem();
        if (bpmWorkItem == null) {
            bpmWorkItem = workFlowManager.getWorkItemById(workItemId);
            Assert.notNull(bpmWorkItem);
            approveParam.setBpmWorkItem(bpmWorkItem);
        }
        if (MaterialBaseConst.AUDIT_PASSED.equals(approveState)) {
            // 如果已指定申请单位领导人员，那么设置下
            if (StrUtil.isNotEmpty(approveParam.getWorkshopApprover())) {
                workFlowManager.setProcessInstanceRelatedData(bpmWorkItem.getProcInstId(), "workshopApprover", approveParam.getWorkshopApprover());
            }
            // 完成工作项，并生成重定向链接
            boolean completeFlag = workFlowManager.completeWorkItem(workItemId);
            Assert.isTrue(completeFlag);

            // 判断当前工作项是否是 “库管组长确认”工作项，如果是则表示审核通过，则执行出库即可
            String workItemName = bpmWorkItem.getName();
            if (StrUtil.contains(workItemName, "库管组长确认")) {
                // 1、执行出库
                MaterialBaseEntity materialBase = materialBaseService.queryObject(approveParam.getId());
                Assert.notNull(materialBase);
                materialBaseService.stockOut(materialBase);
            } else if (StrUtil.contains(workItemName, "申请单位业务主管审核")) {
                /*
                    移动审批会在ERMS中直接指定申请单位领导
                    PC端会跳转到ICHANGAN中进行
                 */
                // 移动审批时会直接指定申请单位领导(workshopApprover)，所以workshopApprover 不为空时表示移动端审批
                if (StrUtil.isNotEmpty(approveParam.getWorkshopApprover())) {
                    SysUserEntity workshopApprover = userService.queryByUnionId(approveParam.getWorkshopApprover());
                    if (workshopApprover != null) {
                        MaterialBaseEntity materialBase = materialBaseService.queryObject(approveParam.getId());
                        Assert.notNull(materialBase);
                        materialBase.setApproverUser(workshopApprover);
                        noticeManager.pushLldspNotice(materialBase);
                    }
                }
            } else if (StrUtil.contains(workItemName, "库管员确认")) {
                // 1、如果是库管员确认后，回填库管员姓名、标记为待出库
                MaterialBaseEntity materialBase = materialBaseService.queryObject(approveParam.getId());
                Assert.notNull(materialBase);
                materialBase.setStoreker(ShiroUtils.getUserId());
                materialBase.setIsOk(1);
                materialBase.setProgress(MaterialBaseProgress.WAIT_OUTBOUND);
                materialBaseService.update(materialBase);
                // 2、如果是维修领料的话，需要生成备件换件记录
                if (NumberUtil.equals(MaterialBaseConst.REPAIR_MATERIAL, materialBase.getMaterialType())) {
                    sparePartConsumRecordService.generateByRepairMaterial(materialBase);
                } else if (NumberUtil.equals(MaterialBaseConst.MAINTENANCE_MATERIAL, materialBase.getMaterialType())) {
                    sparePartConsumRecordService.generateByPmMaterial(materialBase);
                }
            }
            // 审核通过，重定向到下一流程
            directUrl = "/BPMClient/bpmdesktop/missionmanage/Missionredirect.jsf?workItemId=" + workItemId;
        } else {
            // 审批不通过时回退
            workFlowManager.gobackActivityInstance(bpmWorkItem.getActivityInstId(), approveParam.getCheckRemark());
            // 审核不通过，回退到上一流程
            directUrl = "/BPMClient/bpmdesktop/missionmanage/Missionexecute.jsf?workitemId=" + workItemId + "&rollback=true";
        }
        // 记录OA审批结果
        processService.generateProcessHandleRecord(approveParam);
        return directUrl;
    }
}
